# coding:utf-8
# @Time    : 2021/11/29 16:23
# @Author  : Martin
from typing import Dict

from page_object.base.base_page import BasePage
from util.excel_write import write_excel
from util.exe_page_object import exec_po


class PageItems(BasePage):

    def input_phone_num(self, param):
        """
        输入手机号码
        :param param:
        :return:
        """
        self.input('id', 'applyTel', param)

    def input_act_name(self, txt):
        """
        输入活动名称
        :param txt:
        :return:
        """
        self.input('id', 'activityName', txt)

    def input_act_time(self, times: str):
        start_time, end_time = times.split(',')

        """
        输入活动时间
        :param txt:
        :return:
        """
        # self.remove_readonly('id', 'applyBeginDate')
        self.js_input('#applyBeginDate', start_time)
        # iframe1 = self.locate('xpath', '//iframe[@hidefocus="true"]')
        # self.switch_frame(iframe1)
        # 点击确定
        # confirm = self.locate('css selector', '#dpOkInput')
        # self.excute_js("arguments[0].click();", confirm)

        # self.switch_default()

        # self.remove_readonly('id', 'applyEndDate')
        self.js_input('#applyEndDate', end_time)
        # iframe2 = self.locate('xpath', '//iframe[@hidefocus="true"]')
        # self.switch_frame(iframe2)

        # 点击确定
        # confirm = self.locate('css selector', '#dpOkInput')
        # self.excute_js("arguments[0].click();", confirm)
        # self.switch_default()

    def input_act_show_info(self, txt):
        """
        输入活动展示信息
        :param txt:
        :return:
        """
        # parent = self.locate('id', 'tr-activityDisplayInfo')
        # is_display = parent.is_displayed()
        # if is_display:
        self.input('id', 'activityDisplayInfo', txt)
        # else:
        #     self.logger.warn('活动展示信息控件页面不展示，未执行输入')

    def check_act_bu(self, bu_ids: str):
        """
        勾选事业部
        :param bu_ids:
        :return:
        """
        bu_ids = bu_ids.split(',')
        for bu in bu_ids:
            self.single_checked('xpath', f'//input[@value="{bu}"][@name="promotionMaster.divisionCode"]')
            # el = self.locate('css selector', f'input[value="{bu}"][name="promotionMaster.divisionCode"]')
            # self.excute_js('arguments[0].click();',el)
            # loc_text =  f'input[value="{bu}"][name="promotionMaster.divisionCode"]'
            # self.excute_js(f"document.querySelector('{loc_text}').click();")

        # document.querySelector("#divisionCodeTd > div:nth-of-type(1) > input:checked~label")
        # self.click('css selector','#divisionCodeTd > div:nth-child(1) > label:before')
        # js = "return window.getComputedStyle(document.querySelector('#divisionCodeTd > div:nth-child(1) > label'),':before');"
        # js = "document.querySelector('#divisionCodeTd > div').click();"
        # aa = self.excute_js(js)

    def check_channel(self, channel_ids):
        """
        勾选终端
        :param channel_ids:
        :return:
        """
        channel_ids = str(channel_ids).split(',')
        for channel in channel_ids:
            self.single_checked('xpath',
                                f'//input[@value="{channel}"][@name="promotionMaster.activityAccessPointCode"]')

    def check_store_type(self, store_type_ids):
        """
        选择业态类型
        :param store_type_ids:
        """
        store_type_ids = str(store_type_ids).split(',')
        for store_type in store_type_ids:
            self.single_checked('xpath', f'//input[@value="{store_type}"][@name="selectStore"]')

        # 点击全选添加到列表
        self.click('id', 'addalls4')

    def select_part_city(self):
        """
        点击部分城市
        :return:
        """
        self.click('id', 'cityActRadio')

    def select_part_store(self):
        """
        点击部分门店
        :return:
        """
        self.click('id', 'storeActRadio')

    def select_province(self, province_ids):
        """
        选择省份
        :param province_ids:省份
        ('xpath', f'//input[@value="{province}"][@name="province"]')
        """
        province_ids = str(province_ids).split(',')
        for province in province_ids:
            self.scroll_single_checked('#s1', f'input[value="{province}"][name="province"]')
            # self.single_checked('xpath', f'//input[@value="{province}"][@name="province"]')

    def select_area(self, area_ids):
        """
        选择省份
        :param area_ids:大区
        ('xpath', f'//input[@value="{province}"][@name="area"]')
        """
        # 勾选大区选项
        self.single_checked('xpath', '//input[@name="selectArea"][@value="2"]')
        area_ids = str(area_ids).split(',')
        for area in area_ids:
            self.scroll_single_checked('#s1', f'input[value="{area}"][name="area"]')

    def select_city(self, city_ids):
        """
        选择城市
        :param city_ids:
        :return:
        """
        city_ids = str(city_ids).split(',')
        for city in city_ids:
            self.select('name', 's2', city)
        self.click('id', 'add')

    def select_store(self, store_ids):
        """
        选择门店
        :param store_ids:
        :return:
        """
        # 选择门店
        # 点击全选，带出门店
        self.click('id', 'addalls')

        # 遍历选中门店
        store_ids = str(store_ids).split(',')
        for store in store_ids:
            self.select('name', 'ss2', store)

        # 点击添加，把已选中的门店添加到列表
        self.click('id', 'addss')

    def input_act_desc(self, desc):
        """
        输入活动描述信息
        :param desc:
        :return:
        """
        self.input('id', 'activityDesc', desc)

    def check_commodity_type(self, type_ids):
        """
        勾选参与互动商品范围类型
        :param type_ids:
        """
        type_ids = str(type_ids).split(',')
        for type_ in type_ids:
            self.single_checked('xpath', f'//input[@value="{type_}"][@name="promotionMaster.commodityType"]')

    def input_coupon_price(self, balance):
        self.input('name', 'freeCouponsRule.couponsPrice', balance)

    def select_coupon_type(self, coupon_type):
        self.select('name', 'freeCouponsRule.couponsType', coupon_type)


    def select_gift_post_type(self, param):
        """
        赠品配送方式
        :param param:
        :return:
        """
        self.click('xpath', f'//input[@name="limitCondition.distributeLimit"][@value="{param}"]')

    def select_distribute_limit(self, params):
        # limit ={'1':'配送','2':'自提'}
        for param in params:
            self.single_checked('xpath', f'//input[@name="type_distributeLimit"][@value="{param}"]')

    def input_act_count(self, txt=None):
        """
        活动总次数
        :param txt:
        :return:
        """
        if txt:
            self.input('name', 'limitCondition.totalCount', txt)

    def input_act_quato(self, txt=None):
        """
        活动总额度
        :param txt:
        :return:
        """

        if txt:
            self.input('name', 'limitCondition.allQuato', txt)

    def input_person_count(self, txt=None):
        """
        每人活动期间参加次数
        :param txt:
        :return:
        """
        if txt:
            self.input('name', 'limitCondition.joinCount', txt)

    def input_person_day_count(self, txt=None):
        """
        每人每天参加次数
        :param txt:
        :return:
        """
        if txt:
            self.input('name', 'limitCondition.perDayCount', txt)

    def input_act_limit(self, params):
        """
        动态输入活动总次数，总额度，每人每天次数
        :param params:
        :return:
        """
        for k, v in params:
            getattr(self, k)(self, v)

    def select_maintain_type(self, type_):
        self.single_checked('xpath', f'//input[@name="promotionMaster.maintainType"][@value="{type_}"]')

    def _select_commdty_area_type(self, type_):
        """
        选择维护商品范围类型
        :param type_:
        singleType=单品添加
        cateType=目录添加
        brandType=品牌添加
        cateAndBrandType=目录品牌添加
        allCateType=添加全目录
        """
        self.single_checked('xpath', f'//input[@name="cmmdAreaType_radio"][@id="{type_}"]')

    def _select_commdty_bu(self, bu):
        """
        选择商品范围事业部
        :param bu:
        :return:
        """
        self.select('id', 'devisionCode', bu)

    def _select_relation(self, txt):
        """
        选择包含关系
        :param txt: 0：包含 1：排除
        :return:
        """
        self.select('id', 'cmmdAreaType', txt, 'text')

    def _input_cmmd(self, txt):
        self.input('id', 'cmmdCode', txt)

    def _input_cate(self, txt):
        self.input('id', 'cmmdCate', txt)

    def _input_brand(self, txt):
        self.input('id', 'brand', txt)

    def _input_commdty_scope(self, bu=None, code=None, cate=None, brand=None):
        if bu:
            self._select_commdty_bu(bu)
        if code:
            self._input_cmmd(code)
        if cate:
            self._input_cate(cate)
        if brand:
            self._input_brand(brand)

    def add_single(self, params):
        """
        添加单品包含
        :param params:商品范围列表
        :return:
        """
        self._select_relation('包含')
        params = str(params).split(',')
        for param in params:
            bu, cmcode = param.split('_')
            self._select_commdty_bu(bu)
            self._input_cmmd(cmcode)
            self.click('id', 'cmmdCodeAdd')
        self.click('link text', '添加到商品范围')

    def add_single_exclude(self, txt):
        """
        添加单品排除
        :param txt:
        :return:
        """
        self._select_relation('排除')
        codes = str(txt).split(',')
        for code in codes:
            bu, cmcode = code.split('_')
            self._select_commdty_bu(bu)
            self._input_cmmd(cmcode)
            self.click('id', 'cmmdCodeAdd')
        self.click('link text', '添加到商品范围')

    def add_cate(self, txt):
        """
        添加目录包含
        :param txt:
        :return:
        """
        self.click('id', 'cateType')
        self._select_relation('包含')
        codes = str(txt).split(',')
        for code in codes:
            bu, cate = code.split('_')
            self._select_commdty_bu(bu)
            self._input_cate(cate)
            self.click('id', 'cmmdCateAdd')
        self.click('link text', '添加到商品范围')

    def add_cate_exclude(self, txt):
        """
        添加目录排除
        :param txt:
        :return:
        """
        self.click('id', 'cateType')
        self._select_relation('排除')
        codes = str(txt).split(',')
        for code in codes:
            bu, cate = code.split('_')
            self._select_commdty_bu(bu)
            self._input_cate(cate)
            self.click('id', 'cmmdCateAdd')
        self.click('link text', '添加到商品范围')

    def add_brand(self, txt):
        """
        添加品牌包含
        :param txt:
        :return:
        """
        self.click('id', 'brandType')
        self._select_relation('包含')
        codes = str(txt).split(',')
        for code in codes:
            bu, brand = code.split('_')
            self._select_commdty_bu(bu)
            self._input_brand(brand)
            self.click('xpath', '//a[@onclick="brandAdd()"]')
        self.click('link text', '添加到商品范围')

    def add_brand_exclude(self, txt):
        """
        添加品牌排除
        :param txt:
        :return:
        """
        self.click('id', 'brandType')
        self._select_relation('排除')
        codes = str(txt).split(',')
        for code in codes:
            bu, brand = code.split('_')
            self._select_commdty_bu(bu)
            self._input_brand(brand)
            self.click('xpath', '//a[@onclick="brandAdd()"]')
        self.click('link text', '添加到商品范围')

    def add_cate_brand(self, txt):
        """
        添加目录品牌包含
        :param txt:
        :return:
        """
        self.click('id', 'cateAndBrandType')
        self._select_relation('包含')
        codes = str(txt).split(',')
        for code in codes:
            bu, cate, brand = code.split('_')
            self._select_commdty_bu(bu)
            self.input('id', 'cmmdCate', cate)
            self.click('id', 'cmmdCateAdd')
            self.input('id', 'brand', brand)
            self.click('xpath', '//a[@onclick="brandAdd()"]')
            self.click('link text', '添加到商品范围')

    def add_cate_brand_exclude(self, txt):
        """
        添加目录品牌排除
        :param txt:
        :return:
        """
        self.click('id', 'cateAndBrandType')
        self._select_relation('排除')
        codes = str(txt).split(',')
        for code in codes:
            bu, cate, brand = code.split('_')
            self._select_commdty_bu(bu)
            self.input('id', 'cmmdCate', cate)
            self.click('id', 'cmmdCateAdd')
            self.input('id', 'brand', brand)
            self.click('xpath', '//a[@onclick="brandAdd()"]')
            self.click('link text', '添加到商品范围')

    def import_act_scope(self, params):
        """
        批量导入商品范围
        :param params:
        :return:
        """
        index = 0
        for param in params:
            params[index] = param.split('_')
            index += 1

        path = '/excel_template/activityScopeTemplate.xls'
        write_excel(path, params)

        self.click('id', 'batch')
        # 确认切换维护方式 '商品范围维护方式切换时会删除已添加的商品范围！'
        self.switch_alert()
        # 确认商品商品范围成功 '删除已导入的商品范围成功！'
        self.switch_alert()
        self.upload('id', 'singleFile', path)
        self.click('xpath', '//a[@onclick="importActivityScope();"]')
        # 确认导入结果 '本次导入数据2条数据，成功2条，重复0条！'
        return self.switch_alert()

    def _click_save(self):
        self.click('id', 'evaluateSaveBtn')

    def _click_submit(self):
        self.click('id', 'evaluateSubmitBtn')

    def save_draft(self):
        """
        保存草稿
        :return:
        """
        self.click('xpath', '//a[text()="保存"]')

    def input_res_manage(self, percent=None, def_fac_scale=None):
        """

        :param percent:
        :param def_fac_scale:
        :return:
        """

        self.input('name', 'limitCondition.usePercent', percent)
        self.input('name', 'limitCondition.factoryScale', def_fac_scale)

    def go_to_res_manage(self):
        """
        进入资源管理页面
        :return:
        """
        self._click_submit()

    def input_use_scale(self, txt):
        self.js_input('#usePercentResourceHidden', txt,event='onchange')

    def select_company_bu_res(self):
        """
        选择公司+事业部
        :return:
        """
        self.select('id', 'resourceDimensionType', '01')
        self.click('xpath', '//input[@value="设置资源"]')

    def select_company_bu_brand_res(self):
        """
        选择公司+事业部+品牌
        :return:
        """
        self.select('id', 'resourceDimensionType', '02')
        self.click('xpath', '//input[@value="设置资源"]')

    def select_company_store_res(self):
        """
        选择公司+门店
        :return:
        """
        self.select('id', 'resourceDimensionType', '08')
        self.click('xpath', '//input[@value="设置资源"]')

    @staticmethod
    def _get_res_type(param: dict):
        """
        根据输入的资源维度获取类型值
        :param param:
        :return:
        """
        keys = list(param.keys())
        keys.sort()
        # 公司+事业部
        if keys == ['bu', 'company']:
            return '01'
        # 公司+事业部+品牌
        elif keys == ['brand', 'bu', 'company']:
            return '02'
        # 公司+门店
        elif keys == ['company', 'store']:
            return '08'
        else:
            raise ValueError("输入的资源维度类型错误，不在('bu', 'company'),('company','store'),('brand', 'bu', 'company')的组合范围内")

    def input_resource(self, params):
        """
        输入资源信息
        :param params:
        :return:
        """
        # self._select_resource_type(type_)
        rows = self.locates('css selector', '#detailinfoMultiProperProvider>table')
        # for param in params:
        #     param: dict
        #     # type_ = self._get_res_type(param)
        #     index = None
        for row in rows:

            # 获取当前资源行所有信息
            tds = row.find_element('tag name', 'tbody').find_element('tag name', 'tr').find_elements('tag name', 'td')
            # 获取资源行勾选按钮
            checked = tds[0].find_element('id', 'checkMultiProperProvider')
            if not checked.is_selected():
                checked.click()

        for param in params:
            param: Dict
            in_rows = False
            for row in rows:
                # 预期输入的资源行维度信息
                param_expect = [param['company']]
                # 当前资源行维度信息
                param_now = []
                # 获取当前资源行所有信息
                tds = row.find_element('tag name', 'tbody').find_element('tag name', 'tr').find_elements('tag name',
                                                                                                         'td')
                # 公司维度值
                param1 = tds[1].find_element('tag name', 'input').get_attribute('value')
                param_now.append(param1)
                keys = param.keys()
                if 'bu' in keys:
                    # 公司+事业部 公司+事业部+品牌
                    td_i = 2
                    # 预取输入的事业部维度值加入
                    param_expect.append(param['bu'])

                elif 'store' in keys:
                    # 08 公司+门店
                    td_i = 3
                    # 预取输入的门店维度值加入
                    param_expect.append(param['store'])
                else:
                    raise ValueError("资源类型不在[01,02,08]范围内")
                # 事业部 或 门店 维度值
                param2 = tds[td_i].find_elements('tag name', 'input')[1].get_attribute('value')
                param_now.append(param2)
                # 品牌维度值
                if 'brand' in keys:
                    param3 = tds[4].find_element('tag name', 'input').get_attribute('value')
                    param_now.append(param3)
                    param_expect.append(param['brand'])

                # 获取资源行勾选按钮
                checked = tds[0].find_element('id', 'checkMultiProperProvider')
                # 判断 预期输入的资源行维度是否和当前查找到的资源行维度一致
                if param_expect == param_now:
                    in_rows = True
                    if checked.is_selected():
                        checked.click()
                    # 输入预锁总额度 此输入框操作时会弹出必填alert提示，所以改用js设置属性值的方法
                    self.js_input(tds[8].find_element('tag name', 'input'), param['total_lock'], 'onchange')
                    self.js_input(tds[9].find_element('tag name', 'input'), param['fac_scale'], 'onchange')
                    break
            if not in_rows:
                raise ValueError(f'预期 {param_expect}不存在')
        # 如果是总部 临时处理，后续根据登录人账号来判断删除
        del_res = self.locate('xpath', '//span[@id="resourceLineDelBtn"]/input[@value="删除"]')
        if del_res.is_displayed():
            self.logger.info('删除多余的资源行信息')
            del_res.click()

    def cal_after_amount(self, sacle, lock_amount, now_amount):
        """
        计算剩余额度,保留2位小数
        :return:
        """
        self.logger.info(f'预锁比例{sacle}')
        self.logger.info(f'预锁总额{lock_amount}')
        self.logger.info(f'当前额度{now_amount}')
        after_amount = float(now_amount) - round(float(lock_amount) * float(sacle))
        return "%.2f" % after_amount

    def get_exp_res_amount(self, company, bu=None, brand=None, store=None, **kwargs):
        """
        获取预期工厂和我司预期剩余额度
        :param company:
        :param bu:
        :param brand:
        :param store:
        :param kwargs:
        :return:
        """
        rows = self.locates('css selector', '#detailinfoMultiProperProvider>table')

        for row in rows:
            # 获取当前资源行所有信息
            cur_params = {}
            # 入参资源行信息
            params = {}
            tds = row.find_element('tag name', 'tbody').find_element('tag name', 'tr').find_elements('tag name', 'td')
            if company:
                cur_company = tds[1].find_element('tag name', 'input').get_attribute('value')
                cur_params['company'] = cur_company
                params['company'] = company
            if bu:
                cur_bu = tds[2].find_elements('tag name', 'input')[1].get_attribute('value')
                cur_params['bu'] = cur_bu
            if brand:
                # 获取事业部
                cur_brand = tds[4].find_element('tag name', 'input').get_attribute('value')
                cur_params['cur_brand'] = cur_brand
                params['cur_brand'] = brand
            if store:
                # 获取门店值
                cur_store = tds[3].find_elements('tag name', 'input')[1].get_attribute('value')
                cur_params['store'] = cur_store
                params['store'] = store
            # 行信息匹配，则获取额度信息
            if cur_params == params:
                # 获取工厂资源
                fac_amount = tds[11].find_element('tag name', 'input').get_attribute('value')
                # 获取我司资源
                com_amount = tds[15].find_element('tag name', 'input').get_attribute('value')
                # 计算预期工厂剩余额度
                fac_after_amount = self.cal_after_amount(kwargs['fac_scale'], kwargs['total_lock'], fac_amount)
                # 计算我司预期剩余额度
                com_after_amount = self.cal_after_amount(1 - float(kwargs['fac_scale']), kwargs['total_lock'],
                                                         com_amount)

                return fac_after_amount, com_after_amount

        return '不存在预期的资源维度行信息'

    def go_to_approve(self):
        """
        跳转审批弹框，子类会重写，默认是在资源框点确认后弹出审批信息
        :return:
        """

        # # 有资源处理的点击 确定
        # if is_res == 1:
        #     # 有资源处理的点击 确定
        self.click('xpath', '//input[@onclick="resourceConfirmOk();"]')
        # else:
        #     # 无资源处理的 直接点击提交
        #     # submitBtn
        #     # self.click('id', 'evaluateSubmitBtn')
        #     self.click('xpath', '//a[contains(@id,"ubmitBtn")]')

    def input_last_message(self):
        """
        最后一个输入审批文本信息
        :return:
        """
        self.input('name', 'commentContent', '自动化测试')

    def submit_approve(self, approve_info):
        """
        获取审批流程节点信息，遍历审批节点操作
        :param is_res: 是否存资源页面进入审批
        :param approve_info:审批节点信息
        :return:
        """
        print("审批流程节点信息：", approve_info)
        business_code = self.get_business_code()
        setattr(self, 'business_code', business_code)
        print("公文号：", business_code)
        for approve in approve_info:
            # 非首次点击提交
            if 0 < approve_info.index(approve):
                # self.screen_shot()
                self.click('xpath', '//a[contains(@id,"ubmitBtn") or text()="提交"]')
                self.switch_frame(self.locate('xpath', '//iframe[contains(@src,"processCommonSubmit")]'))
                if approve_info.index(approve) < len(approve_info) - 1:
                    self.input('name', 'commentContent', '自动化测试')
                else:
                    self.input_last_message()
            else:
                # 首次提交审批
                self.go_to_approve()
                self.switch_frame(self.locate('xpath', '//iframe[contains(@src,"processCommonSubmit")]'))
            # 进入审批iframe
            self.next_approve(approve['node'], approve['user'], business_code)

    def confirm_approve(self):
        self.click('xpath', '//input[@value="确定"]')
        txt = self.get_element_txt('css selector', '.showErrorMessage')
        if "成功" not in txt:
            raise ValueError(f"审批异常，提示信息为<{txt}>")
        else:
            self.click('xpath', '//input[@onclick="goBackFun()"]')
            self.switch_current_handle()

    def next_approve(self, node, user, act):
        """
        审批对话框，当前审批结束后，自动登录下一审批人
        :param node: 下一审批节点
        :param user: 下一审批人
        :param act: 待审批的活动名称
        :return:
        """
        from page_object import MyJobPage
        from page_object import WelcomePage

        if node != 'SE':
            self.click('xpath', f'//input[@value="{node}"]')

            self.confirm_approve()

            # # 关闭多余窗体
            # [self.close(w) for w in self.driver.window_handles if len(self.driver.window_handles) > 1]
            # # 切换到当前窗体
            # self.switch_current_handle()
            welcome_page = WelcomePage(self.driver, self.logger)
            welcome_page.log_out().log_in(user)
            my_job_page = MyJobPage(self.driver, self.logger)
            my_job_page.go_to_approve(act)
            # 滚动至审批页面底部
            # my_job_page.scroll_bottom()
        else:
            # self.input('name', 'commentContent', '自动化测试')
            # self.click('xpath', '//input[@value="确定"]')
            self.confirm_approve()




    # def input_company_bu_resource(self, param):
    #     self._input_resource(param, '01')
    #
    # def input_company_bu_brand_resource(self, param):
    #     self._input_resource(param, '02')
    #
    # def input_company_store_resource(self, param):
    #     self._input_resource(param, '08')

    def get_business_code(self):
        """
        活动取公文号
        :return:
        """
        return self.get_element_attr('xpath', '//input[@name="promotionMaster.businessCode"]', 'value')

    def do_success(self, steps):
        """
        创建成功包含审批流
        :param steps:
        :return:
        """
        exec_po(self, steps)

    def save_success(self, steps):
        """
        保存草稿
        :param steps:
        :return:
        """
        exec_po(self, steps)
        self.click_save()

if __name__ == '__main__':
    # dd = {'com': 1, 'bu': 2, 'brand': 2, 'store': 2}
    # cc = list(dd.keys())
    # cc.sort()
    # print(cc)
    # print(list(dd.keys())==['a', 'b'])
    # print(PageItems.cal_after_amount('0.11', '100.23', '100.00'))
    print(float(0.1))


